/*
Copyright 2021.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package v1

import (
	"fmt"
	corev1 "k8s.io/api/core/v1"
	nodev1 "k8s.io/api/node/v1beta1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
)

// EDIT THIS FILE!  THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required.  Any new fields you add must have json tags for the fields to be serialized.

// NodePoolSpec 节点池
type NodePoolSpec struct {
	Taints []corev1.Taint    `json:"taints,omitempty"`
	Labels map[string]string `json:"labels,omitempty"`
	// Handler 对应 Runtime Class 的 Handler
	Handler string `json:"handler,omitempty"`
}

func (n *NodePoolSpec) ApplyNode(node corev1.Node) *corev1.Node {
	node.Labels = n.MergeLabels(node.Labels)
	node.Spec.Taints = n.MergeTaints(node.Spec.Taints)
	return &node
}
func (n *NodePoolSpec) MergeLabels(labels map[string]string) map[string]string {
	for k, v := range n.Labels {
		labels[k] = v
	}
	return labels
}

func (n *NodePoolSpec) MergeTaints(taints []corev1.Taint) []corev1.Taint {
	var taintsMap = map[string]corev1.Taint{}

	for _, v := range taints {
		taintsMap[fmt.Sprintf("%s:%s:%s", v.Key, v.Value, v.Effect)] = v
	}

	for _, v := range n.Taints {
		taintsMap[fmt.Sprintf("%s:%s:%s", v.Key, v.Value, v.Effect)] = v
	}
	var allTraints = make([]corev1.Taint, 0, len(taintsMap))
	for _, train := range taintsMap {
		allTraints = append(allTraints, train)
	}
	return allTraints
}

func (n *NodePoolSpec) DelTaints(taints []corev1.Taint) []corev1.Taint {
	var taintsMap = map[string]corev1.Taint{}

	for _, v := range taints {
		taintsMap[fmt.Sprintf("%s:%s:%s", v.Key, v.Value, v.Effect)] = v
	}

	for _, v := range n.Taints {
		delete(taintsMap, fmt.Sprintf("%s:%s:%s", v.Key, v.Value, v.Effect))
	}

	var allTraints = make([]corev1.Taint, 0, len(taintsMap))
	for _, train := range taintsMap {
		allTraints = append(allTraints, train)
	}
	return allTraints
}

func (n *NodePoolSpec) CleanNode(node corev1.Node) *corev1.Node {
	nlabels := node.Labels
	for k := range n.Labels {
		delete(nlabels, k)
	}
	node.Labels = nlabels
	node.Spec.Taints = n.DelTaints(node.Spec.Taints)
	return &node
}

// NodePoolStatus defines the observed state of NodePool
type NodePoolStatus struct {
	// status=200 说明正常，其他情况为异常情况
	Status int `json:"status"`

	// 节点的数量
	NodeCount int `json:"nodeCount"`

	// 允许被调度的容量
	Allocatable corev1.ResourceList `json:"allocatable,omitempty" protobuf:"bytes,2,rep,name=allocatable,casttype=ResourceList,castkey=ResourceName"`
}

//+kubebuilder:printcolumn:JSONPath=".status.status",name=Status,type=integer
//+kubebuilder:printcolumn:JSONPath=".status.nodeCount",name=NodeCount,type=integer
//+kubebuilder:object:root=true
//+kubebuilder:resource:scope=Cluster
//+kubebuilder:subresource:status

// NodePool is the Schema for the nodepools API
type NodePool struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty"`

	Spec   NodePoolSpec   `json:"spec,omitempty"`
	Status NodePoolStatus `json:"status,omitempty"`
}

// NodeRole 返回节点对应的 role 标签名
func (n *NodePool) NodeRole() string {
	return "node-role.kubernetes.io/" + n.Name
}

func (n *NodePool) NodeLabelSelector() labels.Selector {
	return labels.SelectorFromSet(map[string]string{
		n.NodeRole(): "",
	})
}

// RuntimeClass 生成对应的 runtime class 对象
func (n *NodePool) RuntimeClass() *nodev1.RuntimeClass {
	tolerations := make([]corev1.Toleration, len(n.Spec.Taints))
	for i, t := range n.Spec.Taints {
		tolerations[i] = corev1.Toleration{
			Key:      t.Key,
			Value:    t.Value,
			Effect:   t.Effect,
			Operator: corev1.TolerationOpEqual,
		}
	}

	return &nodev1.RuntimeClass{
		ObjectMeta: metav1.ObjectMeta{
			Name: "node-pool-" + n.Name,
		},
		Handler: n.Spec.Handler,
		Scheduling: &nodev1.Scheduling{
			NodeSelector: n.Spec.Labels,
			Tolerations:  tolerations,
		},
	}
}

//+kubebuilder:object:root=true

// NodePoolList contains a list of NodePool
type NodePoolList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata,omitempty"`
	Items           []NodePool `json:"items"`
}

func init() {
	SchemeBuilder.Register(&NodePool{}, &NodePoolList{})
}
